package com.zhangmin.demo.advice;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @description: TODO
 * @author: ZhangMin
 * @date: 2018/06/15
 */
@Component
@Aspect
public class WebControllerAop {
    
    /**
     * 匹配com.zhangmin.demo.controller包及其子包下的所有类的所有方法
     */
    @Pointcut("execution(* com.zhangmin.demo.controller..*.*(..))")
    public void executeService(){

    }

    /**
     * 前置通知，方法调用前被调用
     * @param joinPoint
     */
    @Before("executeService()")
    public void doBeforeAdvice(JoinPoint joinPoint){
        ServletRequestAttributes attributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String beanName = joinPoint.getSignature().getDeclaringTypeName();
        String methodName = joinPoint.getSignature().getName();
        String uri = request.getRequestURI();
        //请求参数
        Object[] paramsArray = joinPoint.getArgs();
        //get方法不记录日志
        if ("GET".equals(request.getMethod())) {
            return;
        }
        System.out.println("uri:" + uri);
        System.out.println("methodName:" + methodName);
        System.out.println("beanName:" + beanName);
        System.out.println("paramsArray:" + JSON.toJSON(paramsArray));
    }


}